package com.example.teesystem.service.impl;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.teesystem.common.cache.CourseCache;
import com.example.teesystem.common.cache.UserCache;
import com.example.teesystem.common.exception.CustomException;
import com.example.teesystem.common.utils.Response;
import com.example.teesystem.common.utils.ResultCode;
import com.example.teesystem.entity.CourseData;
import com.example.teesystem.entity.User;
import com.example.teesystem.entity.vo.courseData.CourseDataSelectVo;
import com.example.teesystem.entity.vo.PageResponseVo;
import com.example.teesystem.filter.MyHandlerInterceptor;
import com.example.teesystem.service.CourseDataService;
import com.example.teesystem.mapper.CourseDataMapper;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
* @author ASUS
* @description 针对表【t_course_data】的数据库操作Service实现
* @createDate 2022-03-31 09:22:05
*/
@Service
@RequiredArgsConstructor
public class CourseDataServiceImpl extends ServiceImpl<CourseDataMapper, CourseData>
    implements CourseDataService{

    private final CourseDataMapper courseDataMapper;

    @Override
    public Response updateStar(Integer id, Float star) {
        CourseData courseData = this.getById(id);
        if(courseData == null) {
            return Response.error(ResultCode.PARAMETER_ERROR);
        }
        if(star < 0 || star > 5){
            return Response.error(ResultCode.PARAMETER_ERROR);
        }
        if(CourseCache.courseMap.get(courseData.getCourseId()).getTeacher() != MyHandlerInterceptor.getUid()) {
            return Response.error(ResultCode.NO_PERMISSION);
        }
        try {
            courseDataMapper.updateStar(id, star);
            return Response.ok();
        }catch (Exception e){
            return Response.error(ResultCode.UPDATE_MESSAGE_ERROR);
        }
    }

    /**
     * 删除课程资料
     * @param id
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Response remove(Integer id){
        if(!this.removeById(id)){
            return Response.error(ResultCode.COURSE_DATA_DELETE_ERROR.getMsg(),ResultCode.COURSE_DATA_DELETE_ERROR.getCode());
        }
        return Response.ok();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Response getDataByCourseId(Integer courseId, Integer cur, Integer size, Integer isPublic,Boolean star) {
        Page<CourseData> page = new Page<>(cur,size);
        List<CourseData> courseDatas;
        List<CourseDataSelectVo> courseDataShow = new ArrayList<>();
        User u = new User();
        u.setMyName("未找到该用户");
        QueryWrapper<CourseData> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId).orderByDesc(star,"star").orderByDesc(true,"upload_time");
        Page<CourseData> myPage = this.page(page,wrapper);
        courseDatas = myPage.getRecords();
        for (CourseData courseData : courseDatas) {
            if(courseData.getIsPublic() == 1){
                CourseDataSelectVo courseDataSelectVo = new CourseDataSelectVo(courseData);
                courseDataSelectVo.setUploadName(UserCache.userMap.getOrDefault(courseData.getUploadId(), u).getMyName());
                courseDataShow.add(courseDataSelectVo);
            }
        }
        return Response.ok(new PageResponseVo<CourseDataSelectVo>(courseDataShow,myPage.getCurrent(), myPage.getSize(), myPage.getPages()));

    }

    /**
     * 获取某人的课程资料
     * @param Uid
     * @param CourseId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Response getCourseDataOfSomebody(Integer Uid, Integer CourseId, Integer cur, Integer size, Boolean star){
        User user1 = new User();
        user1.setMyName("未找到该用户");

        if (Validator.isNull(CourseId)) {
            return Response.error(ResultCode.PARAMETER_MISS.getMsg(), ResultCode.PARAMETER_MISS.getCode());
        }

        Page<CourseData> page = new Page<>(cur, size);
        if(! CourseCache.courseMap.containsKey(CourseId)) {
            return Response.error(ResultCode.COURSE_NOT_EXIST_ERROR.getMsg(), ResultCode.COURSE_NOT_EXIST_ERROR.getCode());
        }
        List<CourseDataSelectVo> courseDataSelectVoList = new ArrayList<>();
        QueryWrapper<CourseData> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", CourseId)
                .eq("upload_id", Uid)
                .orderByDesc(star,"star")
                .orderByDesc(true,"upload_time");;

        Page<CourseData> myPage = this.page(page,wrapper);
        List<CourseData> courseDataList = myPage.getRecords();

        //当Uid非自己，即查询他人上传的资料
        if (Uid != MyHandlerInterceptor.getUid()) {
            if (Validator.isNull(CourseId) || Validator.isNull(Uid)) {
                return Response.error(ResultCode.PARAMETER_MISS.getMsg(), ResultCode.PARAMETER_MISS.getCode());
            }

            User user = UserCache.userMap.get(MyHandlerInterceptor.getUid());
            User target = UserCache.userMap.get(Uid);

            //教师无法查看其他教师上传的非公开内容
            if (user.getType() == 1) {
                for (CourseData courseData : courseDataList) {
                    if (courseData.getIsPublic() == 1 || courseData.getUploadId() == MyHandlerInterceptor.getUid()) {
                        CourseDataSelectVo courseDataSelectVo = new CourseDataSelectVo();
                        BeanUtils.copyProperties(courseData, courseDataSelectVo);
                        courseDataSelectVo.setUploadName(UserCache.userMap.getOrDefault(courseData.getUploadId(), user1).getMyName());
                        courseDataSelectVoList.add(courseDataSelectVo);
                    }
                }
            }
            //非教师无法查看他人的隐私资料
            else {
                for (CourseData courseData : courseDataList) {
                    if (courseData.getIsPublic() == 1 || courseData.getUploadId() == MyHandlerInterceptor.getUid()) {
                        CourseDataSelectVo courseDataSelectVo = new CourseDataSelectVo();
                        BeanUtils.copyProperties(courseData, courseDataSelectVo);
                        courseDataSelectVo.setUploadName(UserCache.userMap.getOrDefault(courseData.getUploadId(), user1).getMyName());
                        courseDataSelectVoList.add(courseDataSelectVo);
                    }
                }
            }
            return Response.ok(new PageResponseVo<CourseDataSelectVo>(courseDataSelectVoList, myPage.getCurrent(), myPage.getSize(), myPage.getPages()));
        }
        //未填入查询ID时Uid为本人ID，查询自己上传的资料
        else {
            for (CourseData courseData : courseDataList) {
                CourseDataSelectVo courseDataSelectVo = new CourseDataSelectVo();
                BeanUtils.copyProperties(courseData, courseDataSelectVo);
                courseDataSelectVo.setUploadName(UserCache.userMap.getOrDefault(courseData.getUploadId(), user1).getMyName());
                courseDataSelectVoList.add(courseDataSelectVo);
            }
            return Response.ok(new PageResponseVo<CourseDataSelectVo>(courseDataSelectVoList, myPage.getCurrent(), myPage.getSize(), myPage.getPages()));
        }
    }


}




